import 'package:cached_network_image/cached_network_image.dart';
import 'package:dali_ng_pera/page/browser/dnp_browser_page.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../certification/dnp_certification_page.dart';
import '../widget/dnp_app_bar.dart';
import 'dnp_order_in_progress_controller.dart';
import 'model/dnp_order_list_model.dart';

class DnpOrderInProgressPage extends StatefulWidget {
  final String title;
  final String state;

  const DnpOrderInProgressPage(
      {super.key, required this.title, required this.state});

  @override
  State<DnpOrderInProgressPage> createState() => _DnpOrderInProgressPageState();
}

class _DnpOrderInProgressPageState extends State<DnpOrderInProgressPage> {
  final controller = Get.put(DnpOrderInProgressController());

  @override
  void initState() {
    super.initState();
    controller.onRequestData(widget.state);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF53A9FF),
              Color(0xFFDFF1FF),
            ],
          ),
        ),
        child: Column(
          children: [
            DnpAppBar(title: widget.title),
            Expanded(child: _buildOrderList())
          ],
        ),
      ),
    );
  }

  Widget _buildOrderList() {
    return Obx(() {
      if (controller.orderList.value.isEmpty) {
        return _buildOrderEmpty();
      }
      return ListView.builder(
        itemCount: controller.orderList.value.length,
        padding: EdgeInsets.only(top: 2),
        itemBuilder: (context, index) {
          return _buildOrderItem(controller.orderList[index]);
        },
      );
    });
  }

  Widget _buildOrderItem(DnpOrderListModel model) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        if ((model.lover ?? "").isNotEmpty) {
          if(model.lover?.startsWith("http") == true){
            Get.to(DnpBrowserPage(path: model.lover ?? ""));
          }else {
            handleJump(model.lover ?? "", "");
          }
        }
      },
      child: Container(
        width: double.infinity,
        margin: EdgeInsets.only(left: 14, right: 14, top: 14),
        padding: EdgeInsets.all(14),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/ic_order_in_progress_item_bg.webp"),
            fit: BoxFit.fill,
          ),
        ),
        child: Column(
          children: [
            _buildOrderAvatar(model),
            _buildOrderContentItem(model),
            _buildOrderCheckItem(model)
          ],
        ),
      ),
    );
  }

  Widget _buildOrderAvatar(DnpOrderListModel model) {
    return Row(
      children: [
        CachedNetworkImage(
          imageUrl:model.griesbach ?? "",
          width: 39,
          height: 39,
        ),
        SizedBox(
          width: 9,
        ),
        Text(
          model.tossing ?? "",
          style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w700,
              color: Color(0xFF333333)),
        )
      ],
    );
  }

  Widget _buildOrderContentItem(DnpOrderListModel model) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 10),
      padding: EdgeInsets.only(top: 5, bottom: 5),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16), color: Color(0xFFE9F5FF)),
      child: Column(
        children: model.wrapped
                ?.map((e) => _buildOrderContentChildItem(
                    e.discernible ?? "", e.hedge ?? ""))
                .toList() ??
            [],
      ),
    );
  }

  Widget _buildOrderContentChildItem(String title, String content) {
    return Container(
        width: double.infinity,
        margin: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
        child:
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Text(title,
              style: TextStyle(
                  fontWeight: FontWeight.w400,
                  fontSize: 14,
                  color: Color(0xFF333333))),
          Text(content,
              style: TextStyle(
                  fontWeight: FontWeight.w400,
                  fontSize: 14,
                  color: Color(0xFF333333)))
        ]));
  }

  Widget _buildOrderCheckItem(DnpOrderListModel model) {
    return Container(
      margin: EdgeInsets.only(top: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            onTap: () {
              if ((model.rank ?? "").isNotEmpty) {
                Get.to(DnpBrowserPage(path: model.rank ?? ""));
              }
            },
            child: Text(
              model.growths ?? "",
              style: TextStyle(
                  fontWeight: FontWeight.w600,
                  decoration: TextDecoration.underline,
                  fontSize: 14,
                  color: Color(0xFF252630)),
            ),
          ),
          Container(
            height: 39,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 27),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: Color(0xFF1D4AC8),
            ),
            child: Text(
              model.earnestly ?? "",
              style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildOrderEmpty() {
    return Column(
      children: [
        SizedBox(
          height: 134,
        ),
        Image.asset(
          "assets/images/ic_order_list_empty.webp",
          width: 255,
          height: 204,
        ),
        Text(
          "No more records.",
          style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w400,
              color: Color(0xFF878787)),
        ),
      ],
    );
  }

  /// 解析URL参数
  ///
  /// 例如: @ios://Dali.ngPe.ra/aisle?already=1&name=test
  /// 返回: {
  ///   'scheme': 'ios',
  ///   'host': 'Dali.ngPe.ra',
  ///   'path': '/aisle',
  ///   'queryParameters': {'already': '1', 'name': 'test'}
  /// }
  Map<String, dynamic> parseUrlParameters(String url) {
    // 移除开头的@符号（如果存在）
    String cleanUrl = url.trim();
    if (cleanUrl.startsWith('@')) {
      cleanUrl = cleanUrl.substring(1);
    }

    try {
      Uri uri = Uri.parse(cleanUrl);

      return {
        'scheme': uri.scheme,
        'host': uri.host,
        'path': uri.path,
        'queryParameters': uri.queryParameters,
      };
    } catch (e) {
      print('URL解析失败: $e');
      return {
        'scheme': '',
        'host': '',
        'path': '',
        'queryParameters': <String, String>{},
      };
    }
  }

  /// 获取URL中的查询参数
  ///
  /// 例如: @ios://Dali.ngPe.ra/aisle?already=1&name=test
  /// 返回: {'already': '1', 'name': 'test'}
  Map<String, String> getQueryParameters(String url) {
    return parseUrlParameters(url)['queryParameters'] as Map<String, String>;
  }

  /// 获取URL中指定的参数值
  ///
  /// 例如: getParameterValue('@ios://Dali.ngPe.ra/aisle?already=1', 'already')
  /// 返回: '1'
  String? getParameterValue(String url, String paramName) {
    Map<String, String> params = getQueryParameters(url);
    return params[paramName];
  }

  void handleJump(String src,String title) {
    // 解析URL参数
    Map<String, dynamic> urlInfo = parseUrlParameters(src);
    Map<String, String> params = urlInfo['queryParameters'] as Map<String, String>;

    if (src.startsWith("ios://Dali.ngPe.ra/alikelove")) {
      //设置
      print('参数: $params');
    } else if (src.startsWith("ios://Dali.ngPe.ra/notice")) {
      //首页
      print('参数: $params');
    } else if (src.startsWith("ios://Dali.ngPe.ra/girl")) {
      //登录
      print('参数: $params');
    } else if (src.startsWith("ios://Dali.ngPe.ra/her")) {
      //订单
      print('参数: $params');
    } else if (src.startsWith("ios://Dali.ngPe.ra/aisle")) {
      //产品详情
      print('参数: $params');
      if(params.containsKey("already")){
        Get.to(DnpCertificationPage(already: params['already']!));
      }
    }else if(src.isNotEmpty){
      Get.to(DnpBrowserPage(path: src));
    }
  }
}
